﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Globalization;
using System.Resources;
using Ue.Infrastructure.ResourceFramework;

namespace Ue.Qcdz.Domain.ResourceManager
{
    public class ResourceGlobals
    {
        #region 单例

        private static class ResourceHolder
        {
            public static ResourceGlobals Resources=new ResourceGlobals();
        }

        public static ResourceGlobals Instance
        {
            get { return ResourceHolder.Resources; }
        }

        #endregion

        private readonly string resourceDirectory;
        private IDictionary<string, XmlResourceManager> caches;

        private ResourceGlobals()
        {
            this.resourceDirectory = HttpContext.Current.Server.MapPath("~/Language");
            this.caches = new Dictionary<string, XmlResourceManager>();
        }

        public SiteUrl GetUrl(string key)
        {
            SiteUrl siteUrl = this.BuildResourceManager("SiteUrls").GetObject(key) as SiteUrl;
            if(siteUrl!=null)
            {
                siteUrl.Name=key;
            }

            return siteUrl;
        }

        public string GetString(string key)
        {
            return this.BuildResourceManager("Strings").GetString(key);
        }

        public StringDictionary GetLanguages()
        {
            StringDictionary languageDictionary = new StringDictionary();

            XmlResourceManager languageResourceManager = this.BuildResourceManager("Language");
            ResourceSet resourceSet = languageResourceManager.GetResourceSet(new CultureInfo("zh-cn"), false, false);
            if (resourceSet != null)
            {
                IDictionaryEnumerator enumerator = resourceSet.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    languageDictionary.Add(enumerator.Key.ToString(), enumerator.Value.ToString());
                }
            }

            return languageDictionary;
        }

        #region private methods

        private XmlResourceManager BuildResourceManager(string resourceFileBaseName)
        {
            if (!this.caches.ContainsKey(resourceFileBaseName))
            {
                lock (this.caches)
                {
                    if (!this.caches.ContainsKey(resourceFileBaseName))
                    {
                        XmlResourceManager xmlResourceManager = new XmlResourceManager(this.resourceDirectory, resourceFileBaseName);

                        this.caches.Add(resourceFileBaseName, xmlResourceManager);
                    }
                }
            }

            return this.caches[resourceFileBaseName];
        }

        #endregion
    }
}
